﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon;
using Baosight.ZNH.ZMCP.UI.Blocks;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCP.UI.PopWindows;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Telerik.Windows.Controls;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using System.Windows.Browser;

namespace Baosight.ZNH.ZMCP.UI
{
    /// <summary>
    /// 防突专业计划
    /// </summary>
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 张志芳
    /// Version: 1.0
    /// History:
    ///       2011-10-24  张志芳   [创建]
    ///       2013-05-08  王开兵   [修改：系统当前日期在20号到28之间的时候，所有防突专业计划都是可以修改的]
    ///
    public partial class ZMCP09 : EFViewCmes
    {
        ProfessionalPlanBlock block = new ProfessionalPlanBlock();
        private string actionType;
        public int modifyStartDate; //每月可以修改所有计划的起始日期
        public int modifyEndDate; //每月可以修改所有计划的终止日期
        public int CurentDay; //保存服务器当前系统时间

        public ZMCP09()
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
        }

        /// <summary>
        /// 新增/修改前设置属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="initData"></param>
        public override void Initialize(Platform.Core.EIInfo initData)
        {
            modifyStartDate = int.Parse(initData.Get("fdModifyStartDate").ToString());
            modifyEndDate = int.Parse(initData.Get("fdModifyEndDate").ToString());
            CurentDay = int.Parse(initData.Get("currentDate").ToString().Substring(8, 2));

            initData.AddBlock(block.getPlanStatus("cmes.cp.planStatus", true));
            initData.AddBlock(block.getPlanMonth("cmes.cp.planMonth", true));
            base.Initialize(initData);
        }

        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            base.OnInsertButtonClickPopup(eiInfo, "防突专业计划-新增", "insert", null, sender, e);
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");

            EIRow row = new EIRow();
            if (_list.Count > 0)
            {
                row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            }

            eIBlock.SetRow(0, row);
            eiInfo.AddBlock(eIBlock);

            this.actionType = "update";
            base.OnUpdateButtonClickPopup(eiInfo, "防突专业计划-修改", "update", null, sender, e);
        }

        /// <summary>
        /// 删除按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            this.actionType = "delete";
            base.OnDeleteButtonClick(sender, e);
        }

        /// <summary>
        /// 点击上报事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnReportButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (BeforeAction != null)
            {
                BeforeAction.Invoke(null, null);
            }

            int count = this.ViewProperty.EFGridCheckedRows.Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行上报！", true);
                return;
            }
            else if (count > 1)
            {
                this.OpenEFWindowAlert("最多只能选择一条记录进行上报！", true);
                return;
            }
            else
            {
                if ("上报".Equals(this.ViewProperty.EFGridCheckedRows[0]["fdPlanStatus"].ToString()))
                {
                    base.OpenEFWindowAlert("已经上报的记录，不能再次上报！", true);
                    return;
                }
                else
                {
                    DialogParameters param = this.ModelDialogParameters("Confirm", "确定所选择上报的记录？");
                    param.Closed = ModifyConfirmClosed;
                    EFWindow.Confirm(param);
                }
            }

        }

        /// <summary>
        /// “改变状态”按钮的确认框，点击确认按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ModifyConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);//取消后，“改变状态”按钮生效
                return;
            }
            if (e.DialogResult.Value)
            {
                base.Submit(OperationMode.Update, "ZMCP09", "report", DataRange.CheckedItems, DoModifyOperationCompleted);
            }
        }

        /// <summary>
        /// 执行修改“改变状态”后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private new void DoModifyOperationCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                string _msg;
                if (inInfo.GetMsg() == null || inInfo.GetMsg() == "")
                {
                    _msg = "操作失败！";
                }
                else
                {
                    _msg = inInfo.GetMsg();
                }

                this.OpenEFWindowAlert(_msg, true);//修改状态按钮执行失败后，按钮生效
                return;
            }
            else
            {
                base.UpdateData(e.EIInfo);
                this.TempButtonOpen(true);//修改状态按钮执行成功后，按钮生效

                this.UpdateHomePageData(e.EIInfo);
                this.AfterMethod(e.EIInfo);
            }
        }

        /// <summary>
        /// 打印某个月的报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPrintButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (BeforeAction != null)
            {
                BeforeAction.Invoke(null, null);
            }

            int count = this.ViewProperty.EFGridCheckedRows.Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行打印！", true);
                return;
            }
            else if (count > 1)
            {
                this.OpenEFWindowAlert("只能选择一条记录进行打印！", true);
                return;
            }
            else
            {
                string fdKeyId = this.grid.GetCheckedEIRows()[0]["fdKeyId"].ToString();
                string fdPlanYear = this.grid.GetCheckedEIRows()[0]["fdPlanYear"].ToString();
                string fdPlanMonth = this.grid.GetCheckedEIRows()[0]["fdPlanMonth"].ToString();
                string planLastMoth = (int.Parse(fdPlanMonth)-1).ToString();
                string planLastYear = fdPlanYear;
                if (fdPlanMonth.Equals("1"))
                {
                    planLastMoth = "12";
                    planLastYear = (int.Parse(fdPlanYear) - 1).ToString();
                }
                Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=ProfessionalPlan&reportName=professionalFTReport&fdKeyId=" + fdKeyId + "&year=" + fdPlanYear + "&month=" + fdPlanMonth + "&lastMonth=" + planLastMoth + "&lastYear=" + planLastYear);
                HtmlPage.Window.Navigate(uri, "_blank");
                base.TempButtonOpen(true);//按钮生效
            }

        }

        /// <summary>
        /// 删除,修改前的判断
        /// </summary>
        /// <param name="rowList"></param>
        /// <returns></returns>
        public override bool BeforeMethod(List<EIRow> _eIRows)
        {
            bool Flag = true;
            ////获取当前日期
            //int CurentDay = int.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd").Substring(8, 2));
            //判断系统当前日期是否在设置可以修改所有计划的日期范围内
            if (CurentDay < modifyStartDate || CurentDay > modifyEndDate)
            {
                if ("update".Equals(this.actionType))
                {
                    if (!"草拟".Equals(_eIRows[0]["fdPlanStatus"].ToString()))
                    {
                        base.OpenEFWindowAlert("只能对草拟的记录进行修改！", true);
                        Flag = false;
                    }
                }
                else if ("delete".Equals(this.actionType))
                {
                    foreach (var row in _eIRows)
                    {
                        if (!"草拟".Equals(row["fdPlanStatus"].ToString()))
                        {
                            base.OpenEFWindowAlert("只能对草拟的记录进行删除！", true);
                            Flag = false;
                            break;
                        }
                    }
                }
            }
            //else if ("report".Equals(this.actionType))
            //{
            //    foreach (var row in _eIRows)
            //    {
            //        if ("上报".Equals(row["fdPlanStatus"].ToString()))
            //        {
            //            base.OpenEFWindowAlert("已经上报的记录，不能再次上报！", true);
            //            Flag = false;
            //            break;
            //        }
            //    }
            //}
            return Flag;
        }

        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            ProfessionalPlanFT professionalPlan = new ProfessionalPlanFT(_dialogType);//构造一个新的修改页面
            professionalPlan.EIDataContext = new Platform.Core.UI.EIDataContext();

            _eIInfo.AddBlock(block.getPlanMonth("cmes.cp.planMonth", false));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.department"));

            professionalPlan.EIDataContext.Update(_eIInfo);

            if("insert".Equals(_dialogType))
            {
                professionalPlan.fdPlanYear.Value = DateTime.Now.Year.ToString();
                professionalPlan.fdPlanMonth.Value = DateTime.Now.Month.ToString();
                professionalPlan.fdEditDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
                professionalPlan.fdPlanType.Value = "防突计划";
                professionalPlan.fdPlanStatus.Value = "草拟";
                professionalPlan.fdCreateDepartmentId.Value = this.EIDataContext.GetAttribute("fdCreateDepartmentId");
                professionalPlan.fdCreateDepartment.Value = this.EIDataContext.GetAttribute("fdCreateDepartment");
                professionalPlan.fdCreatorId.Value = this.EIDataContext.GetAttribute("fdCreatorId");
                professionalPlan.fdCreator.Value = this.EIDataContext.GetAttribute("fdCreator");
                //(professionalPlan.fdCreatorId.Content as CmesCustomView).Display= this.EIDataContext.GetAttribute("fdCreator");
            }

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = professionalPlan;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
           
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmesWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.grid.Refresh();
            }

            //按钮生效
            base.TempButtonOpen(true);

            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 选中主表一条记录，显示该条记录的从表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            RefreshViewData();
        }

        /// <summary>
        /// 选择从表tab页签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabType_SelectionChanged(object sender, RoutedEventArgs e)
        {
            RefreshViewData();
        }

        /// <summary>
        /// 刷新tab页签页面
        /// </summary>
        private void RefreshViewData()
        {
            if (tabType.SelectedItem != null)
            {
                EFTabItem item = tabType.SelectedItem as EFTabItem;
                item.Content = null;
                if (this.grid.SelectedItem != null)
                {
                    Dictionary<string, string> args = new Dictionary<string, string>();
                    args.Add("fdProfessionalplanId", this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null).ToString());
                    args.Add("fdPlanYear", this.grid.SelectedItem.GetType().GetProperty("fdPlanYear").GetValue(this.grid.SelectedItem, null).ToString());
                    args.Add("fdPlanMonth", this.grid.SelectedItem.GetType().GetProperty("fdPlanMonth").GetValue(this.grid.SelectedItem, null).ToString());
                    args.Add("fdPlanStatus", this.grid.SelectedItem.GetType().GetProperty("fdPlanStatus").GetValue(this.grid.SelectedItem, null).ToString());

                    if (item.Name.Equals("tab1"))
                    {
                        item.LoadView("ZMCP0A", args);
                    }
                    else if (item.Name.Equals("tab2"))
                    {
                        item.LoadView("ZMCP0B", args);
                    }
                    else if (item.Name.Equals("tab3"))
                    {
                        item.LoadView("ZMCP0C", args);
                    }
                    else if (item.Name.Equals("tab4"))
                    {
                        item.LoadView("ZMCP0D", args);
                    }
                }                
            }
        }
    }
}
